<template>
    <el-dialog
        id="my-dialog"
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        :header-class="custom-header" 
        :body-class="custom-body"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
            style="margin-top: -15px;"
        >
            <el-collapse class="title" style="margin-bottom:10px"> 
                <div class="collapse-header" @click="toggleCollapse">
                    <span>基础信息</span>
                    <div style="display: flex;align-items: center;">
                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                        <img
                            v-if="isCollapsed"
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                        />
                        <img
                            v-else
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                        />
                    </div>
                </div>
                <div v-show="!isCollapsed" class="collapse-content1">
                    <el-row>
                        <el-col :span="16">
                            <el-form-item label-width="120px" label="采购订单编号:">
                                <el-tooltip
                                    placement="top"
                                    v-for="(item,index) in entityObj.purchaseOrders"
                                    :key="item.purchaseOrderId"
                                >
                                    <template #content>
                                        要货单位: {{item.storeName}}
                                        <br />
                                        申请人:{{item.purchaseName}}
                                        <br />
                                        申请时间:{{item.purchaseDate}}
                                        <br />
                                        期望到货时间:{{item.expectedDate}}
                                        <br />
                                        发货状态:{{item.sendStatusDesc}}
                                    </template>
                                    <span
                                        style="color: blue;margin-right: 5px;"
                                    >{{item.purchaseOrderCode}}{{ index !== entityObj.purchaseOrders.length - 1 ? ',' : '' }}</span>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label-width="155px" label="收货门店:" prop="storeName">
                                <el-input v-model="entityObj.storeName" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="155px" label="收货人:" prop="realName">
                                <el-input v-model="entityObj.realName" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="155px" label="收货手机号:" prop="realName">
                                <el-input v-model="entityObj.mobile" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label-width="155px" label="收货地址:" prop="address">
                                <el-input v-model="entityObj.address" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="155px" label="出库时间:" prop="sendDate">
                                <el-date-picker
                                    v-model="entityObj.sendDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    format="YYYY-MM-DD HH:mm:ss"
                                />
                                <!--  <el-input v-model="entityObj.sendDate" /> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label-width="155px"
                                label="物流公司:"
                                :prop="this.entityObj.isLocalSupplier==0?'logisticsCode':''"
                            >
                                <el-select
                                    placeholder="---请选择物流公司---"
                                    v-model="entityObj.logisticsId"
                                    style="width: 100%"
                                >
                                    <el-option label="---请选择---" value />
                                    <el-option
                                        v-for="item in optionsLogistics"
                                        :key="item.logisticsId"
                                        :label="item.logisticsName"
                                        :value="item.logisticsId"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                label-width="155px"
                                label="配送物流单号/车牌:"
                                :prop="this.entityObj.isLocalSupplier==0?'logisticsCode':''"
                            >
                                <el-input v-model="entityObj.logisticsCode" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label-width="155px" label="备注">
                                <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label-width="155px" label="附件上传">
                                <sc-upload-file
                                    v-model="entityObj.sendFiles"
                                    :objName="'Supply/sendOrder'"
                                    draggable
                                    :uploadType="'OSS'"
                                    :bucketName="'jtmc'"
                                    :limit="9"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-collapse>
            <el-collapse class="title">
                <div class="collapse-header" @click="toggleCollapse1">
                    <span>发货信息</span>
                    <div style="display: flex;align-items: center;">
                        <span class="expand-text">{{ isCollapsed1 ? '展开' : '收起' }}</span>
                        <img
                            v-if="isCollapsed1"
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                        />
                        <img
                            v-else
                            class="icon-img"
                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                        />
                    </div>
                </div>
                <div v-show="!isCollapsed1" class="collapse-content1">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label-width="80px" label="出库发货:">
                                <el-form inline label-width="49px">
                                    <el-form-item label="物料编号" label-width="80px">
                                        <el-input
                                            placeholder="---请输入编号---"
                                            v-model="queryList.materialCode"
                                            style="width: 160px"
                                        />
                                    </el-form-item>
                                    <el-form-item label="物料名称" label-width="80px">
                                        <el-input
                                            placeholder="---请输入名称---"
                                            v-model="queryList.materialName"
                                            style="width: 160px"
                                        />
                                    </el-form-item>
                                    <el-form-item label="物料分类" label-width="80px">
                                        <el-tree-select
                                            v-model="queryList.materialTypeIds"
                                            collapse-tags
                                            collapse-tags-tooltip
                                            placeholder="---请选择物料分类---"
                                            :props="{ label: 'label', value: 'value', children: 'children' }"
                                            :data="materialTypeTree"
                                            multiple
                                            :render-after-expand="false"
                                            show-checkbox
                                            style="width: 160px"
                                        />
                                    </el-form-item>
                                    <el-button
                                        :icon="Search"
                                         
                                        type="primary"
                                        @click="handleSearch"
                                    >查询</el-button>
                                    <el-button
                                        :icon="Search"
                                        type="info"
                                        plain
                                        @click="resetSearch"
                                    >重置</el-button>
                                    <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                                </el-form>
                            </el-form-item>
                            <el-table
                                    :data="itemsData"
                                    border
                                    style="width: 100%"
                                    show-summary
                                    :summary-method="getSummaries"
                                >
                                    <!-- <el-table-column label="物料编码" width="110" prop="materialCode"></el-table-column> -->
                                    <el-table-column label="物料名称" min-width="150" prop="materialName">
                                        <template #default="scope">
                                            <div
                                                v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                                style="color: #318cf2;"
                                                @click="handlePreview(scope.row)"
                                            >{{scope.row.materialName}}</div>
                                            <div v-else>{{scope.row.materialName}}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="规格" min-width="130" prop="materialSpecs"></el-table-column>
                                    <!-- <el-table-column label="物料类别" width="85" prop="materialTypeName"></el-table-column> -->
                                    <el-table-column label="单位" min-width="90" prop="unitName"></el-table-column>
                                    <el-table-column label="配送单价" min-width="100" prop="price"></el-table-column>
                                    <!-- <el-table-column label="类型" width="70" prop="purchaseOrderTypeDesc"></el-table-column> -->
                                    <el-table-column label="本次发货" min-width="130">
                                        <template #default="scope">
                                            <el-input-number
                                                :disabled="scope.row.sendQty>=scope.row.receiveQty"
                                                :max="scope.row.receiveQty-scope.row.sendQty"
                                                v-model="scope.row.qty"
                                                style="width: 100%"
                                                :precision="0"
                                                :step="1"
                                                controls-position="right"
                                            ></el-input-number>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="应发货" min-width="80" prop="receiveQty"></el-table-column>
                                    <el-table-column label="已发货" min-width="80" prop="sendQty"></el-table-column>
                                    <el-table-column label="待发货" min-width="80">
                                        <template
                                            #default="scope"
                                        >{{scope.row.receiveQty-scope.row.sendQty }}</template>
                                    </el-table-column>
                                    <el-table-column label="发货照片" min-width="150">
                                        <template #default="scope">
                                            <el-image
                                                v-for="(item,index) in scope.row.sendFiles"
                                                :key="index"
                                                style="width: 50px; height: 40px;margin: 4px;"
                                                :src="item"
                                                :zoom-rate="1.2"
                                                :max-scale="7"
                                                :min-scale="0.2"
                                                :preview-src-list="[item]"
                                                preview-teleported="true"
                                                :z-index="9999"
                                                fit="cover"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" min-width="100">
                                        <template #default="scope">
                                            <el-button
                                                type="primary"
                                                size="small"
                                                @click="opUploadFile(scope.row)"
                                            >上传</el-button>
                                        </template>
                                    </el-table-column>
                                    <!-- <el-table-column label="累计退货" width="85" prop="returnedQty">
                                    </el-table-column>-->

                                    <!-- <el-table-column label="配送金额" width="90" prop="totalAmount"></el-table-column>
                                    <el-table-column label="备注" width="140" prop="remarks"></el-table-column>
                                    <el-table-column label="出库仓库" width="140" prop="warehouseId">
                                        <template #default="scope">
                                            <el-select
                                                :disabled="scope.row.sendQty>=scope.row.receiveQty"
                                                placeholder="---请选择出库仓库 ---"
                                                v-model="scope.row.warehouseId"
                                                style="width: 100%"
                                            >
                                                <el-option label="---请选择---" value />
                                                <el-option
                                                    v-for="item in scope.row.warehouses"
                                                    :key="item.warehouseId"
                                                    :label="item.warehouseName"
                                                    :value="item.warehouseId"
                                                />
                                            </el-select>
                                        </template>
                                    </el-table-column>-->
                                </el-table>
                        </el-col>
                    </el-row>
                </div>
            </el-collapse>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >确认出库发货</el-button>
        </template>

        <!-- <template>
            <el-dialog v-model="materialState" title="选择商品" :width="1000" :center="true" append-to-body
                style="height: 480px">
                <el-row>
                    <sc-material-choice ref="scMaterialChoice"></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>-->
    </el-dialog>
    <!-- 预览组件 -->
    <el-image-viewer
        v-if="showImage"
        @close="closeViewer"
        :hide-on-click-modal="true"
        :url-list="srcList"
    />
    <upload-files-dialog
        v-if="dialogUploadFiles"
        ref="uploadFilesDialog"
        @setSendFiles="setSendFiles"
        @success="handleSaveSuccess"
        @closed="dialogUploadFiles = false"
    ></upload-files-dialog>
</template>



<script>
import tool from "@/utils/tool";
import uploadFilesDialog from "./uploadFiles";
export default {
    emits: ["success", "closed"],
    components: {
        uploadFilesDialog,
    },
    data() {
        return {
            mode: "Send",
            titleMap: {
                Send: "发货",
            },
            entityObj: {},
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            dialogUploadFiles: false,
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            //验证规则
            rules: {
                realName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                mobile: [{ required: true, type: "string", message: "请填写" }],
                address: [
                    { required: true, type: "string", message: "请填写" },
                ],
                // storeName: [
                //     { required: true, type: "string", message: "请填写" },
                // ],
                sendDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                logisticsId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                logisticsCode: [
                    { required: true, type: "string", message: "请填写" },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsLogistics: [],
            itemsData: [],
            currentRow: {}, //上传照片当前行
            isCollapsed: true,
            isCollapsed1: false,
        };
    },
    computed: {
        // itemsData() {
        //     let filtered = this.entityObj.purchaseProtocolItems;
        //     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
        //         filtered = filtered.filter(item => {
        //             return this.queryList.materialTypeIds.includes(item.materialTypeId);
        //         });
        //     }
        //     if (this.queryList.materialCode) {
        //         filtered = filtered.filter(item => {
        //             return item.materialCode.includes(this.queryList.materialCode);
        //         });
        //     }
        //     if (this.queryList.materialName) {
        //         filtered = filtered.filter(item => {
        //             return item.materialName.includes(this.queryList.materialName);
        //         });
        //     }
        //     return filtered;
        // },
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //图片预览
        handlePreview(row) {
            console.log("row", row.materialImages);
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        toggleCollapse1() {
            this.isCollapsed1 = !this.isCollapsed1; // 切换展开/收起状态
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "purchase-order/send",
                                {
                                    ...this.entityObj,
                                    logisticsName: this.optionsLogistics.find(
                                        (p) =>
                                            p.logisticsId ==
                                            this.entityObj.logisticsId
                                    )?.logisticsName,
                                }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "purchase-order/send-detail",
                    { purchaseOrderIds: data }
                );
                if (returnValue.status == 200) {
                    this.entityObj = {
                        ...returnValue.response,
                        logisticsId: null,
                        logisticsCode: "",
                        sendDate: tool.formatDate(new Date()),
                    };
                    console.log("采购订单", this.entityObj);
                    this.queryList = {};
                    this.handleSearch();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "logistics/current",
                    {}
                );
                if (returnValue.status == 200) {
                    this.optionsLogistics = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        handleSearch() {
            this.itemsData = this.entityObj.sendOrderItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            console.log(this.entityObj.purchaseProtocolItems);
        },

        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) =>
                    Number(item[column.property])
                );

                if (
                    column.property == "receiveQty" ||
                    column.property == "sendQty" ||
                    column.property == "returnedQty" ||
                    column.property == "price" ||
                    column.property == "totalAmount"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                }
            });
            return sums;
        },
        //上传照片
        opUploadFile(row) {
            this.currentRow = row;
            this.dialogUploadFiles = true;
            var data = {
                sendFiles: row.sendFiles,
            };
            this.$nextTick(() => {
                this.$refs.uploadFilesDialog.open("Show").setData(data);
            });
        },

        //设置上传照片
        setSendFiles(sendFiles) {
            this.currentRow.sendFiles = sendFiles ? sendFiles.split(",") : [];
        },
    },
    async mounted() {
        await this.initOptions();
    },
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 8px !important;
}



.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 10px;
    padding-left: 0;
    font-weight: bold;
    font-size: 16px;
}

.expand-text {
    color: #308bf2; /* Element UI 的蓝色 */
    font-size: 14px;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
.collapse-content {
    padding: 10px;
}

.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}

/* 过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.6s ease;
}

.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
    opacity: 0;
}


</style>
